<?php
/**
 * json返回格式助手类
 */
namespace common\helpers;

use yii\helpers\BaseJson;

class ShowJson extends BaseJson
{
    /**
     * @返回json格式的错误数据
     * @param array $errorArr      错误信息数组：如array("code" => xx, "message" => xxx, "data" => array())
     * @return array[]
     */
    public static function showErrorJson($errorArr = array())
    {
        if (!is_array($errorArr)) {
            echo '错误内容格式不正确';
            die();
        }
        if (empty($errorArr)) {
            $code = 100000;
            $message = 'system error';
            $json_data = array('code' => $code, 'message' => $message, 'data' => (object)[]);
        } else {
            if (empty($errorArr['data'])) {
                $errorArr['data'] = (object)[];
            }
            if (!empty($errorArr['message'])) {
                $errorArr['message'] = $errorArr['message'];
            }
            $json_data = $errorArr;
        }
        echo self::encode($errorArr);
        die();
    }
    
    /**
     * 返回json格式的成功数据
     * @param array $data   成功需要返回的数组
     * @return array
     */
    public static function showSuccessJson($data = array())
    {
        if (!is_array($data)) {
            echo '错误内容格式不正确';
            die();
        }
        
        $code = 200;
        $message = 'success';
        if (empty($data)) {
            $data = (object)[];
        }
        $json_data = array('code' => $code, 'message' => $message, 'data' => $data);
        echo self::encode($json_data);
        die();
    }
}
